﻿/*
*-------------------------------
* ValidaForm
* version 1.2 (08/05/2013)
* Autor: Hernán Javier Hegykozi
* Contacto: hernanjh@gmail.com
*-------------------------------
*/
(function() {
		  
		this.ValidationForm = function() {
			this.ValidationForm = ValidationForm.copyProperties (ValidationForm, ValidationForm.Methods);
			return ValidationForm;
			
		};
}
).call(window);


ValidationForm.Methods = {

	/*Options*/
	charSplit: ';',
	cssClass: 'InputImage',
	backgroundColor: "#F4DFDF",
	valido: true,
	
	setOptions: function(options) {
		ValidationForm.copyProperties(this, options);
	},
	
	init: function (param, container)
	{
		this.setOptions(param);
		return this.validate(container);
		
	},
	
	replaceValidChars : function(text) {
		var str = text;
        str = str.replace(/[^\u00e1\u00e9\u00ed\u00f3\u00fa\u00f1\u000a\u000a\u00c1\u00c9\u00cd\u00d3\u00da\u00d1\u000A\u0020-\u007E\u00fc\u00dc\u00b0\u00aa]/g, ' ');
		return str;
	},
	
	validate: function (container)
	{		
        //recorre todos los elementos del formulario
        var cont = "";
        if (typeof container != "undefined" && container!=null && container!="") cont = "#" + container;
        var that = this;
        $(cont+':input').each(function(){
            that.validation($(this));
        });

		return this.valido;

	},

    validation : function (elem, focus)
    {
        if (typeof focus === "undefined" || focus===null) focus = true;
        var lang = "";
        if (elem.hasAttr('lang'))
            lang = elem.attr('lang').split(this.charSplit);

        removeLabelError(elem.attr('id'));

        if (lang != '' && this.isVisible(elem))
        {
		    var inputerror = false;

		    //Si esta vacio me fijo que no sea obligatorio
			if (lang[0] == 'true' && (elem.val() == '' || elem.val() == '0'))
			{
                addLabelError(elem.attr('id'), "El ingreso del campo es obligatorio");
                
				if(this.valido)
				{
                    if (focus)
					    elem.focus();
					this.valido = false; 
                    inputerror = true;
				}
			}
            //valido el tipo de dato
			if (lang.length > 1 && !inputerror && elem.val() != '')
			{				
				if (!this.validatetype(elem,lang))
				{

					addLabelError(elem.attr('id'), "Ingreso erroneo del campo");
					if(this.valido)
					{
                        if (focus)
						    elem.focus();
						this.valido = false; 
                        inputerror = true;
					}
				}				
			}		
        }
        $(".errorlabel").parpadear();

    },

	validatetype: function (elem, lang)
	{
		var error = false;
		if (lang[1] == 'email') 
			if (!isEmail(elem.val()))
				return false;
		
		if (lang[1] == 'url') 
			if (!isUrl(elem.val()))
				return false;
				
		if (lang[1] == 'link') 
			if (!isLink(elem.val()))
				return false;
				
		if (lang[1] == 'numeric') 
			if (!isNumeric(elem.val()))
				return false;
				
		if (lang[1] == 'entero') 
			if (!isInteger(elem.val()))
				return false;
				
		if (lang[1] == 'alfa') 
			if (!IsAlphanumeric(elem.val()))
				return false;
						
		if (lang[1] == 'date') 
			if (!isDate(elem.val()))
				return false;
						
		if (lang[1] == 'money') 
			if (!isMoney(elem.val()))
				return false;
						
		if (lang[1] == 'cuitcuil') 
			if (!isCUITCUIL(elem.val()))
				return false;
						
		if (lang[1] == 'expte') 
			if (!isNroExpediente(elem.val()))
				return false;
						
		if (lang[1] == 'ingreso') 
			if (!isNroIngreso(elem.val()))
				return false;
														
		if (lang[1] == 'NumeracionDoc') 
			if (!isNroDocGenerico(elem.val()))
				return false;
							
		if (lang[1] == 'periodo') 
			if (!isPeriodo(elem.val()))
				return false;
		
		if (lang[1] == 'telefono') 
			if (!isTelefono(elem.val()))
				return false;
				
		if (lang[1] == 'nrotelefono') 
			if (!isNroTelefono(elem.val()))
				return false;						

		if (lang[1] == 'porcentaje') 
			if (!isPorcentaje(elem.val()))
				return false;

		if (lang[1] == 'PeriodoMesAnio') 
			if (!isPeriodoMesAnio(elem.val()))
				return false;	
				
		if (lang.length > 2)
		if (lang[2].length > 0)
        {
		   if(!eval(lang[2]))	
				return false;
        }

		return true;
	},
	
	/*-----------Functions Utils-------------*/
	isVisible : function  (elem)
	{
        if (elem.is(':reallyvisible'))  return true;
        return false;

	},
	Replace: function (texto, bus, rem)
	{
		do { texto = texto.replace(bus,rem);} while(texto.indexOf(bus) >= 0);
		return texto;
	}
	
}


/*-- Utils --------------------------------------------*/
ValidationForm.copyProperties = function(dest, src) {
  for (var property in src) {
    dest[property] = src[property];
  }
  return dest;
};

function validarForm (container)
{
	var nobj = new ValidationForm();
	return nobj.init(container);
}

function validarDialog(container) {
    if (validarForm(container)) {
        $('#' + container).dialog('close');
        return true;
    }
    return false;
}

function validarFormBlurActivo()
{
    $(':input').each(function () {    
     $(document).on("blur", "#"+this.id, function () {
            validarElemento($(this));
            });

       /* $(this).blur(function () {
            validarElemento($(this));
        });*/
    });
}

function validarElemento (jqelem)
{
	var nobj = new ValidationForm();
	nobj.validation(jqelem, false);
}



function addLabelError (element, msg)
{
	var pos = $("#"+element).offset();  
	var width = $("#"+element).width();	
	var msg = $("<span id='"+element+"_error'  class='errorlabel' title='"+msg+"'><img src='/Styles/HerGoS-theme/images/icon_error.png' /></span>");
	//msg.css( { "left": (pos.left + width)+5 + "px", "top":pos.top + "px" } );

    $("#"+element).parent().append(msg);
	$("#"+element).addClass("errorcontrol"); 

}
function removeLabelError (element)
{
	$("#"+element).removeClass("errorcontrol");
	$("#"+element+"_error").remove();
}

//-------------------------------------------------
function isNumeric(Expression)
{
	var numberPat= /^[-+]?[0-9]+[,]?[0-9]*([eE][-+]?[0-9]+)?$/;
	var matchArray = Expression.match(numberPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}
function isInteger(Expression)
{
	var enteroPat= /^[0-9]+$/;
	var matchArray = Expression.match(enteroPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}
function IsAlphanumeric(Expression)
{
	var alphaPat= /^([a-z0-9áéíóúñ.,-/:_ ])*$/i
	var matchArray = Expression.match(alphaPat);
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

function isEmail(emailStr) 
{                   
    var emailPat = /[\w-\.]{2,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/;
	var matchArray = emailStr.match(emailPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

//---VALIDA LA FECHA
function isDate(dateStr) {

	var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		return false;
	}
	month = matchArray[3]; // p@rse date into variables
	day = matchArray[1];
	year = matchArray[5];
	
	if (month < 1 || month > 12) { // check month range
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			return false;
		}
	}
	if (year < 1900) {
		return false;
	}	
	return true; // date is valid
}


//Valida que sea Numerico y que tenga como mucho 2 decimales
function isMoney (moneyStr) 
{
	if (isNumeric(moneyStr))
	{
	    var moneyPat = /^\d+(?:,\d{1,2})?$/;
		var matchArray = moneyStr.match(moneyPat); // is the format ok?
		if (matchArray == null) 
			return false;
		else
			return true;
	}
	else
	{
		return false;	
	}
}


//Valida el Campo de CUIT / CUIL y el digito verificador
function isCUITCUIL(varCUIT)
{
    if (varCUIT == "99999999999")
        return true;
	if ((varCUIT.length==11)&&(!isNaN(varCUIT)))
	{
		var StrCuit=varCUIT;
		var a = 0;
		var x=1 ;
		var n=0;
		var m=0;
		var blnResultado=false;
		for(x = 0; x < 11; x++) 
		{    
			n = parseInt(StrCuit.substr(x,1));
			n = n + 48;
			switch(x+1){
					case 1:	m = 5; break;
					case 2:	m = 4; break;
					case 3: m = 3; break;
					case 4: m = 2; break;
					case 5: m = 7; break;
					case 6: m = 6; break;
					case 7: m = 5; break;
					case 8: m = 4; break;
					case 9: m = 3; break;
					case 10: m = 2; break;
					case 11: m = 1; break;
				
				}					
			a = a +( n * m);
		}
		a = a % 11;
		if (a == 3)
		{blnResultado = true;}    
		else
		{blnResultado = false;}
	}
	else
	{blnResultado = false;}
return blnResultado;
}

function isUrl(urlStr) 
{
    var urlPat = /^(ht|f)tps?:\/\/\w+([\.\-\w]+)?\.([a-z]{2,4}|travel)(:\d{2,5})?(\/.*)?$/i;
	var matchArray = urlStr.match(urlPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

function isLink(linkStr) 
{
    var linkPat = /^[a-zA-Z0-9-_:/.?&amp;=]+$/;
	var matchArray = linkStr.match(linkPat);
	
	if (matchArray == null) 
		return false;
	else
		return true;
}


function isTelefono(telefono)
{

    var linkTel = /^[0-9]{0,5}-?[0-9]{2,4}-? ?[0-9]{4}$/;
	var matchArray = telefono.match(linkTel);
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

function isNroTelefono(telefono)
{
	//Cod. Area: 3 a 5 digitos + num. telefono (celular sin 15)
    var linkTel = /^[0-9]{11}$/;
	var matchArray = telefono.match(linkTel);
	
	if (matchArray == null) 
		return false;
	else
		return true;
}


/*------Funciones específicas------*/
//**************************************************************
function isNroExpediente(Nro)
{
	var fecha = new Date();
	var patt1= new RegExp(/^(\d{1,6})(\/)(\d{2})?$/);
	if (patt1.test(Nro))
	{
		var anio = 	RegExp.$3; //tomo el año
		if ((anio == 96)||(anio == 97)||(anio == 98)||(anio == 99)||(eval(anio) + 2000 <= fecha.getRealYear()))
			return true;
		else
			return false;
	}
	else
	{
		return false;
	}
}
//**************************************************************
function isNroIngreso(Nro)
{
	var fecha = new Date();
	var patt1= new RegExp(/^(\d{1,6})(\/)(\d{4})(\-\d{1,2})?$/);
	if (patt1.test(Nro))
	{
		var anio = 	RegExp.$3; //tomo el año
		if (anio>=1996 && anio <= fecha.getRealYear())
			return true;
		else
			return false;
	}
	else
	{
		return false;
	}
}
//**************************************************************
function isNroDocGenerico(Nro)
{
	var fecha = new Date();
	var patt1= new RegExp(/^(\d{1,7})(\/)(\d{4})?$/);
	if (patt1.test(Nro))
	{
		var anio = 	RegExp.$3; //tomo el año
		if (anio>=1996 && anio <= fecha.getRealYear())
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

//**************************************************************
/*-----CuotaOmitida-----*/

function isPeriodo(Nro)
{
	var fecha = new Date();
	var r = false;
	if (Nro.length == 6)
	{
		var anio = Nro.substring(0, 4);
		var mes = Nro.substring(4, 6);
		if (anio >= 1996 && anio <= fecha.getRealYear())
		{
			if (mes >= 1 && mes <= 12)
			{
				r = true;	
			}
			
		}
		
	}
	return r;
}

/*-----FIN CuotaOmitida-----*/

function isExpedienteCM(expCMStr) 
{
    var expCMPat = /^(\w{3})(\-)([LlPpHh]{1})(\-)(\d{5})(\/)(\d{2})$/;

	var matchArray = expCMStr.match(expCMPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

function isPeriodoMesAnio(Nro){
	var fecha = new Date();
	var r = false;
	var patt1= new RegExp(/^(\d{1,2})(\/)(\d{4})?$/);
	if (patt1.test(Nro)){
		var mes = 	RegExp.$1; //tomo el dia
		var anio = 	RegExp.$3; //tomo el anio
		if ((mes>=1 && mes <= 12) && (anio>=1996 && anio <= fecha.getRealYear()))
			r = true;	
	}
	return r;
}


function isNumerosxComa(str) 
{
	var arr = str.split(",");

	if (arr.length != 0)
	{
		for (var i = 0; i < arr.length; i++)
			if (!isInteger(arr[i]))
					return false;

		return true;
	}
	else
		return false;
}

function isPorcentaje (PorcStr) 
{
	if (isNumeric(PorcStr))
	{
	    if (PorcStr <= 100) 
        {
            var porcPat =  /^(\d{1,3})+(,\d{1,2})?$/;
	        var matchArray = PorcStr.match(porcPat); 
	        if (matchArray == null)
	            return false;
	        else
	            return true;
	    }
	    else
	        return false; 
	}
	else
	{
		return false;	
	}
}



Date.prototype.getRealYear = function() 
{ 
    if(this.getFullYear)
        return this.getFullYear();
    else
        return this.getYear() + 1900; 
};
/*SEGURIDAD*/
/*FUNCIONES DE VALIDACION*/

function ReplaceSecureStr(input)
{
	var newinput;
	var regExpr = "(\"|'|=|<|>|!|[\/]{2}|[-]{2})";
	var re = new RegExp(regExpr, "g");
	newinput = input.replace(re, "");

	return newinput;
}
function SearchInvalidCaracter(input) 
{
    var regExpr = /^(.*("|'|=|<|>|!|[\/]{2}|[-]{2}).*)$/;
    input = input.replace(new RegExp('\\n','g'),'').replace(new RegExp('\\r','g'),'');
		
	var m = new RegExp(regExpr);
	
	if (m.test(input)) 
		return false;
	else
		return true;
}
function SearchTags(input) 
{
    var regExpr = /^(<[^>]*>)$/;
    input = input.replace(new RegExp('\\n','g'),'').replace(new RegExp('\\r','g'),'');
	
	var m = new RegExp(regExpr);
	
	if (m.test(input)) 
		return false;
	else
		return true;
}
/*FIN SEGURIDAD*/